package com.chenx.myapplicationnav.ui.home

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.IOException
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements

class ChinaZ : WebSite() {

    var nextpage = "";
    override fun parse(viewModelScope: CoroutineScope, imagelist: MutableLiveData<List<String>>) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                var url = "";
                if (nextpage == "") {
                    url = "https://sc.chinaz.com/tupian/"
                } else {
                    url = nextpage
                }
                val client = OkHttpClient()
                val request = Request.Builder().url("https://sc.chinaz.com/tupian/").build()
                val response = client.newCall(request).execute()
                val html = response.body?.string()

                if (html != null) {
                    val doc: Document = Jsoup.parse(html)
                    // nextpage=doc.

                    val imageElements: Elements = doc.select(".item")

//                    var listimg=ArrayList<String>();

//                    for(item in imageElements)
//                    {
//                        listimg.add("http:"+item.attr("data-original").replace("_s",""))
//                    }
//                    listimg.add("123");
//                    listimg.add("123");

                    val imageUrls = imageElements.map {
                        "https:" + it.select("img").attr("data-original").replace("_s", "")
                    }

                    nextpage =
                        "https://sc.chinaz.com/tupian/" + doc.select(".nextpage").attr("href")
                    imagelist.postValue(imageUrls)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}